package com.jchy.renderit.displayable;
 
import com.jchy.renderit.core.Dir;
import com.jchy.renderit.core.Displayable;
import com.jchy.renderit.core.Hit;
import com.jchy.renderit.core.Point;

public class Cylinder extends Displayable
{
    public Cylinder()
    {
    }
    
    public Hit intersect(Point prp, Point vrp)
    {
        Hit aHit=new Hit();
        aHit.isHit=false;
        Point utprp, utvrp, utloc, utnormpt;
        Dir utd;
        
        utprp=untransform(prp);
        utvrp=untransform(vrp);
        utd=utprp.toDir(utvrp);
        utd.normalize();
        
        double a, b, c, t1, t2, t, rt;        

        // Intersect untransformed ray starting at utprp
        // in the direction of utd with a cylinder of
        // radius 1.0 in the zx plane and length 1.0 in the y direction
        a=utd.dz*utd.dz+utd.dx*utd.dx;
        b=2.0*utprp.z*utd.dz+2.0*utprp.x*utd.dx;
        c=utprp.z*utprp.z+utprp.x*utprp.x-1.0;
        
        if(b*b >= 4*a*c)
        {
            rt=Math.sqrt(b*b-4.0*a*c);
            t1=(-b+rt)/(2.0*a);
            t2=(-b-rt)/(2.0*a);
        
            double y1=utprp.y+utd.dy*t1;
            double y2=utprp.y+utd.dy*t2;
        
            if((t1>0.00001)&&(t1<t2)&&(y1<1.0)&&(y1>-1.0))
                t=t1;
            else if((t2>0.00001)&&(y2<1.0)&&(y2>-1.0))
                t=t2;
            else return aHit;
        
            aHit.isHit=true;

            utloc=new Point();
            utloc.x=utprp.x+t*utd.dx;
            utloc.y=utprp.y+t*utd.dy;
            utloc.z=utprp.z+t*utd.dz;
            aHit.color=new java.awt.Color(getPrimaryColorRed(),
                                          getPrimaryColorGreen(),
                                          getPrimaryColorBlue());

            utnormpt=new Point();
            utnormpt.x=2.0*utloc.x;
            utnormpt.y=utloc.y;
            utnormpt.z=2.0*utloc.z;
            
            aHit.location=transform(utloc);
            aHit.normpt=transform(utnormpt);
            aHit.ambient=ambient;
            aHit.diffuse=diffuse;
            aHit.phongCoef=phongCoef;
            aHit.phongExp=phongExp;
        }

        return aHit;
    }
        
}